package com.fifth.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fifth.common.pojo.dto.CommonResult;
import com.fifth.common.pojo.entity.Addr;
import com.fifth.user.mapper.AddrMapper;
import com.fifth.user.service.AddrService;
import com.fifth.user.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 第五组
 * @since 2022-09-02
 */
@Service
public class AddrServiceImpl implements AddrService {
    @Autowired
    private AddrMapper addrMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public CommonResult insertAddr(Addr addr) {
        HttpServletRequest request = WebUtils.getRequest();
        //获取请求头
        String token = request.getHeader("token");
        Map map = JSON.parseObject(redisTemplate.opsForValue().get(token), Map.class);
        Map user = (Map) map.get("user");
        addr.setUid((String) user.get("id"));
        int insert = addrMapper.insert(addr);
        if (insert!=0){
            return new CommonResult(2000,"添加成功",null);
        }
        return new CommonResult(5000,"添加失败",null);

    }

    @Override
    public CommonResult findByUid(String uid) {

        QueryWrapper<Addr> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uid",uid);
        List<Addr> addr = addrMapper.selectList(queryWrapper);
        return new CommonResult(2000,"查询成功",addr);
    }

    @Override
    public CommonResult updateById(Addr addr) {
        int i = addrMapper.updateById(addr);
        if (i!=0){
            return new CommonResult(2000,"修改成功",null);
        }
        return new CommonResult(5000,"修改失败",null);
    }

    @Override
    public CommonResult deleteById(String id) {
        int i = addrMapper.deleteById(id);
        if (i!=0){
            return new CommonResult(2000,"删除成功",null);
        }
        return new CommonResult(5000,"删除失败",null);
    }

    @Override
    public CommonResult findAll() {
        HttpServletRequest request = WebUtils.getRequest();
        //获取请求头
        String token = request.getHeader("token");
        Map map = JSON.parseObject(redisTemplate.opsForValue().get(token), Map.class);
        Map user = (Map) map.get("user");
        String id = (String) user.get("id");
        QueryWrapper<Addr> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uid",id);
        List<Addr> addrs = addrMapper.selectList(queryWrapper);
        return new CommonResult(2000,"查询成功",addrs);
    }
}
